<template>
  <div>
    <el-form
      :model="formData"
      inline
      style="display: flex; justify-content: flex-end; margin-top: 10px"
    >
      <el-form-item prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入角色名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="search" type="primary">查找</el-button>
        <el-button @click="openDialog('创建', 'add', null)" type="primary"
          >添加</el-button
        >
      </el-form-item>
    </el-form>

    <el-table v-loading="tableLoading" :data="tableData" border>
      <el-table-column
        align="center"
        label="角色名称"
        prop="name"
      ></el-table-column>
      <el-table-column
        align="center"
        label="说明"
        prop="desc"
      ></el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="openDialog('编辑', 'edit', scope.row)"
            type="primary"
            >编辑</el-button
          >
          <el-button size="mini" @click="deleteData(scope.row)" type="danger"
            >删除</el-button
          >
          <el-button
            size="mini"
            @click="getPermission(scope.row)"
            type="primary"
            >授权</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageInfo.page"
      :page-sizes="[10, 20, 30, 50, 100]"
      :page-size="pageInfo.limit"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total"
    >
    </el-pagination>

    <el-dialog :visible.sync="dialogVisible" :title="dialogTitle" width="500">
      <el-form
        ref="dialogForm"
        :rules="formRules"
        :model="dialogFormData"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="dialogFormData.name"></el-input>
        </el-form-item>
        <el-form-item label="说明" prop="desc">
          <el-input type="textarea" v-model="dialogFormData.desc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button @click="confirm" type="primary">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogTreeVisible"
      :title="dialogTreeTitle"
      width="500"
    >
      <el-tree ref="tree" :data="treeData" show-checkbox node-key="id">
        <span slot-scope="{ data }">
          {{ data.label }}
          <el-tag v-if="data.api" size="mini" type="success">{{ data.api }}</el-tag>
        </span>
      </el-tree>

      <span slot="footer">
        <el-button @click="permissioCancel">取 消</el-button>
        <el-button @click="permissionConfirm" type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "roleManage",
  componentTitle: "角色管理",
  data() {
    return {
      dialogTreeVisible: false,
      dialogTreeTitle: "授权",
      treeData: [],
      tableLoading: false,
      dialogVisible: false,
      dialogTitle: "创建",
      dialogType: "add",
      dialogFormData: {
        name: "",
        desc: "",
      },
      pageInfo: {
        page: 1,
        limit: 10,
        total: 0,
      },
      formData: {
        name: "",
      },
      currentCopyRow: {},
      tableData: [],
      formRules: {
        question: [
          { required: true, message: "请输入问题", trigger: "change" },
        ],
        answer: [{ required: true, message: "请输入回答", trigger: "change" }],
      },
    };
  },
  mounted() {
    this.search();
  },
  methods: {
    getPermission(row) {
      this.currentCopyRow = Object.assign({}, row);
      // 打开授权的dialog框
      this.dialogTreeVisible = true;
      // 请求树形数据
      axios({
        url: "http://192.168.200.251:8888/admin/role/permissions",
        method: "get",
        params: {
          roleId: row.id,
        },
        headers: {
          "Shopping-Admin-Token": sessionStorage.getItem(
            "Shopping-Admin-Token"
          ),
        },
      }).then((res) => {
        console.log("tree", res);
        this.treeData = res.data.data.systemPermissions;

        this.$refs.tree.setCheckedKeys(res.data.data.assignedPermissions);
        // if (res.data.errno === 0) {
        //   this.cancel()
        //   this.$notify.success({title: '添加成功'})

        //   this.search()
        // } else {
        //   this.$notify.error({title: '添加失败'})
        // }
      });
      // 树形数据赋值
    },
    permissioCancel() {
      this.dialogTreeVisible = false;
    },
    permissionConfirm() {
      let rootData = this.$refs.tree.root.childNodes;
      // console.log(this.$refs.tree.root.childNodes)

      // console.log(this.getCheckedTree(rootData))

      console.log(this.currentCopyRow);
      axios({
        url: "http://192.168.200.251:8888/admin/role/permissions",
        method: "post",
        data: {
          permissions: this.getCheckedTree(rootData),
          roleId: this.currentCopyRow.id,
        },
        headers: {
          "Shopping-Admin-Token": sessionStorage.getItem(
            "Shopping-Admin-Token"
          ),
        },
      }).then((res) => {
        console.log(res);
        if (res.data.errno === 0) {
          this.permissioCancel();
          this.$notify.success({ title: "添加成功" });

          this.search();
        } else {
          this.$notify.error({ title: "添加失败" });
        }
      });
    },
    getCheckedTree(nodeList, list = []) {
      nodeList.forEach((item) => {
        // 如果当前节点的childNodes是空数组，那么证明当前节点是最底层节点，最后将当前节点的id push到list中
        if (!item.childNodes.length && item.checked) {
          list.push(item.data.id);
        }

        if (item.childNodes && item.childNodes.length) {
          return this.getCheckedTree(item.childNodes, list);
        }
      });

      return list;
    },
    openDialog(title, type, row) {
      this.dialogVisible = true;
      this.dialogType = type;
      this.dialogTitle = title;

      if (type === "edit") {
        this.$nextTick(() => {
          this.dialogFormData = Object.assign({}, row);
        });
      }
    },
    confirm() {
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          if (this.dialogType === "add") {
            this.addData();
          } else if (this.dialogType === "edit") {
            this.editData();
          }
        } else {
          return false;
        }
      });
    },
    cancel() {
      this.$refs.dialogForm.resetFields();
      this.dialogVisible = false;
    },
    // 添加接口
    addData() {
      axios({
        url: "http://192.168.200.251:8888/admin/role/create",
        method: "post",
        data: {
          name: this.dialogFormData.name,
          desc: this.dialogFormData.desc,
        },
        headers: {
          "Shopping-Admin-Token": sessionStorage.getItem(
            "Shopping-Admin-Token"
          ),
        },
      }).then((res) => {
        if (res.data.errno === 0) {
          this.cancel();
          this.$notify.success({ title: "添加成功" });

          this.search();
        } else {
          this.$notify.error({ title: "添加失败" });
        }
      });
    },
    // 编辑接口
    editData() {
      axios({
        url: "http://192.168.200.251:8888/admin/role/update",
        method: "post",
        data: {
          ...this.dialogFormData,
        },
        headers: {
          "Shopping-Admin-Token": sessionStorage.getItem(
            "Shopping-Admin-Token"
          ),
        },
      }).then((res) => {
        if (res.data.errno === 0) {
          this.cancel();
          this.$notify.success({ title: "编辑成功" });

          this.search();
        } else {
          this.$notify.error({ title: "编辑失败" });
        }
      });
    },
    deleteData(row) {
      this.$confirm("此操作将删除该问题, 是否继续?").then(() => {
        axios({
          url: "http://192.168.200.251:8888/admin/role/delete",
          method: "post",
          data: row,
          headers: {
            "Shopping-Admin-Token": sessionStorage.getItem(
              "Shopping-Admin-Token"
            ),
          },
        }).then((res) => {
          this.$notify.success({ title: "删除成功" });

          this.search();
        });
      });
    },
    search() {
      this.tableLoading = true;

      axios({
        url: "http://192.168.200.251:8888/admin/role/list",
        method: "get",
        params: {
          page: this.pageInfo.page,
          limit: this.pageInfo.limit,
          ...this.formData,
        },
        headers: {
          "Shopping-Admin-Token": sessionStorage.getItem(
            "Shopping-Admin-Token"
          ),
        },
      }).then((res) => {
        this.tableLoading = false;
        this.tableData = res.data.data.list;

        this.pageInfo.total = res.data.data.total;
        console.log(res);
      });
    },
    // 每页多少条切换
    handleSizeChange(value) {
      this.pageInfo.limit = value;

      this.search();
    },
    // 当前页码的切换
    handleCurrentChange(value) {
      this.pageInfo.page = value;

      this.search();
    },
  },
};
</script>
